package gl.java.mq;

import gl.java.umsp.UmspConnectionHandler;
import gl.java.umsp.UmspMessageDecoder;
import gl.java.umsp.UmspMessagePacker;
import gl.java.umsp.UmspMessageUnpacker;
import gl.java.umsp.event.Event;
import gl.java.umsp.event.EventSubscriber;
import gl.java.umsp.gateway.GateWayMessageDispatcher;
import gl.java.umsp.gateway.InnerServiceEventHandler;
import gl.java.umsp.websocket.HttpRequestHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class NettyServer {

    private static Logger log = LoggerFactory.getLogger(NettyServer.class);

    private boolean isStop = false;
    private EventLoopGroup workerGroup;

    public static void stop(NettyServer nettyNetFrame) {
        nettyNetFrame.isStop = true;
        nettyNetFrame.workerGroup.shutdownGracefully();
    }

    public static NettyServer start(final int mPort, final SimpleChannelInboundHandler handler) {
        final NettyServer nettyNetFrame = new NettyServer();
        new Thread() {
            @Override
            public void run() {
                while (!nettyNetFrame.isStop) {
                    nettyNetFrame.listenForever(mPort, handler);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        log.warn("retry connect  forever");
                    }
                }
            }
        }.start();
        return nettyNetFrame;
    }

    private void listenForever(final int port, final SimpleChannelInboundHandler handler) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new UmspMessageUnpacker(),
                                    new UmspMessagePacker(),
                                    new UmspMessageDecoder(),
                                    handler
                            );
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128);

            ChannelFuture f = b.bind(port).sync();
            f.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future)
                        throws Exception {
                    log.info("===============================================");
                    log.info("======  Start  MessageQueueService at port:" + port + "  ===");
                    log.info("===============================================");
                }
            });
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("mq server exception stop:",e);
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
